<?php
require_once 'db/db.php';
require_once 'util/perm.php';

// int -> int
function threadCount( $forumNum ) {
  if( !hasPerm('view.thread.count') ) 
    return -1;

  try {
    $db = openDbConn();
    // XXX does this work? I don't member
    $res = $db->query("SELECT COUNT(id) AS tcount FROM thread WHERE fid = $forumNum;")->fetch(); 
    $cnt = $res['tcount'];
    $res = NULL;
    return $cnt;
  } catch ( PDOException $e ) {
    print "ERROR: " . $e->getMessage() . "<br />";
    die();
  }
}

// int -> obj?
// XXX clean up this uber messy query. Make it quicker mainly.
function getThread($tid) {
  if( !hasPerm('view.thread') ) 
    return -1;

  try {
    $db = openDbConn();
    return $db->query("SELECT
                         thread.id AS id,
                         thread.fid AS fid,
                         thread.mode AS mode
                       FROM thread
                         WHERE thread.id = {$tid};")->fetch(PDO::FETCH_ASSOC);
  } catch ( PDOException $e ) {
    print "ERROR: " . $e->getMessage() . "<br />";
    die();
  }
}

// int -> int -> int -> obj?
// XXX clean up this uber messy query. Make it quicker mainly.
function getThreads($foraNum, $start, $inc) {
  if( !hasPerm('view.thread') ) 
    return -1;

  try {
    $db = openDbConn();
    return $db->query("SELECT
                         thread.id AS id,
                         thread.fid AS fid,
                         thread.mode AS mode,
                           (SELECT inpost.title
                              FROM post AS inpost
                                WHERE post.tid = inpost.tid
                                  AND inpost.rank = (SELECT MIN(inpost2.rank) 
                                                       FROM post AS inpost2 
                                                         WHERE inpost2.tid = inpost.tid)) AS title,
                           (SELECT inpost.datum
                              FROM post AS inpost
                                WHERE post.tid = inpost.tid
                                  AND inpost.rank = (SELECT MIN(inpost2.rank) 
                                                       FROM post AS inpost2 
                                                         WHERE inpost2.tid = inpost.tid)) AS datum,
                         MAX(post.date)
                       FROM thread
                         INNER
                           JOIN post
                             ON post.tid = thread.id
                             WHERE thread.fid = $foraNum
                       GROUP BY thread.id
                       ORDER BY date DESC
                       LIMIT $start,$inc;");
  } catch ( PDOException $e ) {
    print "ERROR: " . $e->getMessage() . "<br />";
    die();
  }
}


?>
